package com.kapcb.authentication.context.core;

import com.alibaba.fastjson2.JSON;
import com.kapcb.common.constant.StringPool;
import com.kapcb.common.model.UserInfo;
import com.kapcb.context.core.ApplicationThreadContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <a>Title: UserInfoFilter </a>
 * <a>Author: kapcb <a>
 * <a>Description: UserInfoFilter <a>
 *
 * @author Kpacb
 * @version 1.0
 * @date 2024/4/27 12:45
 * @since 1.0
 */
@Slf4j
public class UserInfoFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String userInfoJsonString = request.getHeader(StringPool.USER_ID);
        if (StringUtils.isBlank(userInfoJsonString)) {
            filterChain.doFilter(request, response);
            return;
        }

        try {
            UserInfo userInfo = JSON.parseObject(userInfoJsonString, UserInfo.class);
            ApplicationThreadContextHolder.putUserInfo(userInfo);
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            log.error("UserInfoFilter doFilterInternal error", e);
            filterChain.doFilter(request, response);
        } finally {
            ApplicationThreadContextHolder.clearContext();
        }
    }

}
